import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { useTranslation } from "react-i18next";
import { useCallback, useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useCookies } from "react-cookie";
import { TOKEN } from "@/constants/cookies";
import { useUser } from "@/hooks/use-user";
import { useUserUpdate } from "@/hooks/use-user";
import { usePasswordUpdate } from "@/hooks/use-user";
import { usePasswordSet } from "@/hooks/use-user";
import { useAvatar } from "@/hooks/use-avatar";
import { useFileUpload } from "@/hooks/use-file-upload";
import Avatar from "@/components/custom-ui/avatar";
import { ProfileInfo } from "./components/info";
import { PasswordChange } from "./components/password";
import { AccountBinding } from "./components/account-binding";
import { DeleteAccount } from "./components/delete-account";
import { PasswordPromptDialog } from "./components/password-prompt-dialog";
import { Edit, X, Save, Key } from "lucide-react";
import dayjs from "dayjs";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  ProfileSchema,
  PasswordSchema,
  type ProfileFormData,
  type PasswordFormData,
} from "@/schemas/profile";
import type { UserResponseData } from "@/types/response";

export default function Profile() {
  const { t } = useTranslation();

  // 格式化时间为浏览器本地时区
  const formatToLocalTime = useCallback((dateString: string): string => {
    const date = dayjs(dateString);
    return date.isValid() ? date.format("YYYY-MM-DD HH:mm:ss") : dateString;
  }, []);

  const navigate = useNavigate();
  const [cookies] = useCookies([TOKEN]);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [isChangingPassword, setIsChangingPassword] = useState(false);
  const [showPasswordPrompt, setShowPasswordPrompt] = useState(false);
  const [temporaryAvatarUrl, setTemporaryAvatarUrl] = useState<string | null>(
    null
  );
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { user } = useUser();
  const { updateUser, isUpdating } = useUserUpdate();
  const { updatePassword, isUpdating: isPasswordUpdating } =
    usePasswordUpdate();
  const { setPassword, isSetting: isPasswordSetting } = usePasswordSet();
  const { avatarUrl, loading: avatarLoading } = useAvatar(user?.image);
  const { uploadFileAsync, isUploading, data: fileData } = useFileUpload();

  // 创建个人资料表单
  const form = useForm<ProfileFormData>({
    resolver: zodResolver(ProfileSchema()),
    defaultValues: {
      image: fileData?.data.id,
      name: "",
      first_name: "",
      last_name: "",
      address: "",
      region: "",
    },
  });

  // 创建密码修改表单
  const passwordForm = useForm<PasswordFormData>({
    resolver: zodResolver(PasswordSchema()),
    defaultValues: {
      current_password: "",
      new_password: "",
      confirm_password: "",
    },
  });

  // 进入编辑模式
  const handleEdit = () => {
    if (user) {
      form.reset({
        image: user.image || "",
        name: user.name || "",
        first_name: user.first_name || "",
        last_name: user.last_name || "",
        address: user.address || "",
        region: user.region || "",
      });
      setIsEditing(true);
    }
  };

  // 取消编辑
  const handleCancel = () => {
    setIsEditing(false);
    if (user) {
      form.reset({
        image: user.image || "",
        name: user.name || "",
        first_name: user.first_name || "",
        last_name: user.last_name || "",
        address: user.address || "",
        region: user.region || "",
      });
    }
  };

  // 保存编辑
  const handleSave = (data: ProfileFormData) => {
    updateUser(data);
    setIsEditing(false);
  };

  // 开始修改密码
  const handleStartChangePassword = () => {
    console.log("用户点击修改密码按钮");
    console.log("用户数据:", user);
    console.log("用户是否有密码:", user?.has_password);
    
    // 检查用户是否有密码，如果没有则显示提示弹窗
    if (!user?.has_password) {
      console.log("用户没有密码，显示弹窗");
      setShowPasswordPrompt(true);
    } else {
      console.log("用户已有密码，直接进入修改密码模式");
      setIsChangingPassword(true);
    }
  };

  // 取消修改密码
  const handleCancelChangePassword = () => {
    setIsChangingPassword(false);
    
    // 如果用户仍然没有设置密码，再次显示密码提示弹窗
    if (!user?.has_password) {
      setShowPasswordPrompt(true);
    }
  };

  // 保存密码修改
  const handleSavePassword = (data: PasswordFormData) => {
    // 根据用户是否有密码来决定调用哪个API
    if (user?.has_password) {
      // 用户已有密码，调用更新密码API
      updatePassword({
        current_password: data.current_password || "",
        new_password: data.new_password,
        confirm_password: data.confirm_password,
      });
    } else {
      // 用户没有密码，调用设置密码API
      setPassword({
        new_password: data.new_password,
        confirm_password: data.confirm_password,
      });
    }
    setIsChangingPassword(false);
  };

  // 处理设置密码按钮点击
  const handleSetPassword = () => {
    setShowPasswordPrompt(false);
    setIsChangingPassword(true);
  };

  // 处理图片上传
  const handleImageUpload = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const file = event.target.files?.[0];
    if (file) {
      try {
        const result = await uploadFileAsync(file);
        console.log("文件上传成功:", result);
        form.setValue("image", result.data.id);
        // 设置临时头像URL，立即显示新头像
        const newAvatarUrl = `/api/file/image/${result.data.id}`;
        setTemporaryAvatarUrl(newAvatarUrl);
      } catch (error) {
        console.error("文件上传失败:", error);
        // 错误处理已经在 useFileUpload hook 中处理
      }
    }
  };

  // 点击头像触发文件选择
  const handleAvatarClick = () => {
    if (isEditing && fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  const checkLoginStatus = useCallback(async () => {
    try {
      // 使用react-cookie检查是否有access_token Cookie
      const hasToken = !!cookies.access_token;

      if (!hasToken) {
        navigate(`/cas/login`);
        return;
      }

      setIsLoggedIn(true);
    } catch (error) {
      console.error("Failed to check login status:", error);
      // 检查失败也视为未登录
      navigate(`/cas/login`);
    }
  }, [cookies, navigate]);

  useEffect(() => {
    // 检查用户是否已登录
    checkLoginStatus();
  }, [checkLoginStatus]);

  // 当用户数据加载完成后，检查是否需要显示密码提示弹窗
  useEffect(() => {
    if (user && !user.has_password) {
      console.log("用户没有设置密码，自动显示弹窗");
      setShowPasswordPrompt(true);
    }
  }, [user]);

  if (!isLoggedIn) {
    return (
      <div className="flex items-center justify-center py-12">
        <Card className="w-full min-w-xs max-w-md border border-white/20">
          <CardHeader className="text-center">
            <h2 className="text-2xl font-bold">
              {t("Checking Authentication", {
                defaultValue: "Checking Authentication",
              })}
            </h2>
          </CardHeader>
          <CardContent className="text-center">
            <p>
              {t("Redirecting to login page...", {
                defaultValue: "Redirecting to login page...",
              })}
            </p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="flex items-center justify-center py-12">
      <Card className="w-full min-w-xs max-w-md border border-white/20">
        <CardHeader className="text-center">
          <h2 className="text-2xl font-bold">
            {isChangingPassword
              ? t("Change Password", { defaultValue: "Change Password" })
              : t("User Profile", { defaultValue: "User Profile" })}
          </h2>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-4">
            {/* 用户头像 */}
            <Avatar
              avatarUrl={avatarUrl}
              avatarLoading={avatarLoading}
              isEditing={isEditing}
              isUploading={isUploading}
              onAvatarClick={handleAvatarClick}
              onImageUpload={handleImageUpload}
              fileInputRef={fileInputRef}
              temporaryAvatarUrl={temporaryAvatarUrl}
            />

            {/* 用户信息 - 在修改密码模式下隐藏 */}
            {!isChangingPassword && (
              <ProfileInfo
                user={user as UserResponseData | null}
                isEditing={isEditing}
                form={form}
                formatToLocalTime={formatToLocalTime}
              />
            )}

            {/* 账户绑定 - 在修改密码模式下隐藏 */}
            {!isChangingPassword && (
              <AccountBinding />
            )}

            {/* 删除账户 - 在修改密码模式下隐藏 */}
            {!isChangingPassword && (
              <DeleteAccount />
            )}

            {/* 密码修改表单 - 在用户信息外部 */}
            {isChangingPassword && (
              <PasswordChange
                passwordForm={passwordForm}
                onSavePassword={handleSavePassword}
                hasPassword={user?.has_password}
              />
            )}
          </div>

          {/* 编辑按钮区域 - 固定在底部 */}
          <div className="pt-2 flex justify-center gap-4">
            {!isEditing && !isChangingPassword ? (
              <>
                <Button
                  variant="ghost"
                  onClick={handleEdit}
                  className="w-1/2 hover:cursor-pointer"
                >
                  <Edit className="w-4 h-4" />
                  {t("Edit", { defaultValue: "Edit" })}
                </Button>
                <Button
                  variant="ghost"
                  onClick={handleStartChangePassword}
                  className="w-1/2 hover:cursor-pointer"
                >
                  <Key className="w-4 h-4" />
                  {t("Change Password", { defaultValue: "Change Password" })}
                </Button>
              </>
            ) : isEditing ? (
              <>
                <Button
                  variant="outline"
                  onClick={handleCancel}
                  className="w-1/2 hover:cursor-pointer"
                >
                  <X className="w-4 h-4" />
                  {t("Cancel", { defaultValue: "Cancel" })}
                </Button>
                <Button
                  onClick={form.handleSubmit(handleSave)}
                  disabled={isUpdating}
                  className="w-1/2 hover:cursor-pointer"
                >
                  <Save className="w-4 h-4" />
                  {isUpdating
                    ? t("Saving...", { defaultValue: "Saving..." })
                    : t("Save", { defaultValue: "Save" })}
                </Button>
              </>
            ) : (
              <>
                <Button
                  variant="outline"
                  onClick={handleCancelChangePassword}
                  className="w-1/2 hover:cursor-pointer"
                >
                  <X className="w-4 h-4" />
                  {t("Cancel", { defaultValue: "Cancel" })}
                </Button>
                <Button
                  onClick={passwordForm.handleSubmit(handleSavePassword)}
                  disabled={isPasswordUpdating || isPasswordSetting}
                  className="w-1/2 hover:cursor-pointer"
                >
                  <Save className="w-4 h-4" />
                  {(isPasswordUpdating || isPasswordSetting)
                    ? t("Saving...", { defaultValue: "Saving..." })
                    : t("Save", { defaultValue: "Save" })}
                </Button>
              </>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 密码提示弹窗 */}
      <PasswordPromptDialog
        open={showPasswordPrompt}
        onOpenChange={setShowPasswordPrompt}
        onSetPassword={handleSetPassword}
      />
    </div>
  );
}
